package com.watson.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author watson
 * @date 2021/8/2 14:53
 * @Description: TODO
 **/
public class LocksDemo2 {
    public static void main(String[] args) {
        Phone2 phone = new Phone2();
        new Thread(() -> {
            phone.sms();
        }, "A").start();
        new Thread(() -> {
            phone.sms();
        }, "B").start();

    }
}

class Phone2 {
    Lock lock = new ReentrantLock();

    public void sms() {
        lock.lock(); //第一把锁
        try {
            System.out.println(Thread.currentThread().getName() + "sms");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

        call();
    }

    public void call() {
        lock.lock(); //第二把锁
        //lock 锁必须配对，否则就会死在里面
        // 例如这里两次lock.lock() 后面 一次 lock.unlock();就形成死锁
        try {
            System.out.println(Thread.currentThread().getName() + "call");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

